package com.greyshark.lib.bluetooth.utils

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class JoyTimeoutManager {
  private val scope: CoroutineScope = CoroutineScope(Dispatchers.Main)

  private val jobs = mutableMapOf<TimeoutEnum, Job>()

  fun start(key: TimeoutEnum, timeoutMillis: Long, onTimeout: () -> Unit) {
    cancel(key)
    jobs[key] = scope.launch {
      delay(timeoutMillis)
      onTimeout()
    }
  }

  fun cancel(key: TimeoutEnum) {
    jobs[key]?.cancel()
    jobs.remove(key)
  }

  fun cancelAll() {
    jobs.values.forEach { it.cancel() }
    jobs.clear()
  }

  enum class TimeoutEnum {
    CONNECT_TIMEOUT,
    DISCOVER_SERVICE_TIMEOUT
  }
}
